package tv_megazineplus

import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.Produces
import javax.ws.rs.QueryParam
import javax.ws.rs.DefaultValue
import javax.ws.rs.core.Response
import groovy.sql.Sql
import com.google.gson.Gson
import org.codehaus.groovy.runtime.TimeCategory


@Path('/api/getStatsXML')
class GetStatsXMLResource {

    @GET
    @Produces('application/xml')
    List<Estatistica> getGetStatsXMLRepresentation(@QueryParam('begin') String dtInicio, @QueryParam('end') String dtFim) {
         def t1 = System.currentTimeMillis()
        if(dtInicio ==null || dtFim ==null){
            return ""
        }
        def statss = []
        
       def sql = Sql.newInstance( 'jdbc:postgresql://localhost:5432/ad', 'postgres',
                       'postgres', 'org.postgresql.Driver' )
        sql.eachRow( 'select name, description, media,frequencia from servicos t1 join (select servico_id ,avg(total_time) as media ,COUNT(servico_id) as frequencia FROM statistic where date between \''+dtInicio+'\' and \''+dtFim+'\' group by servico_id) t2 on t1.id = t2.servico_id' ) {
           statss.add(new Estatistica(name:it.name,description:it.description,media:it.media,frequencia:it.frequencia))
        }
        def tt = System.currentTimeMillis() - t1        
        new Statistic(servico: Servicos.findByName('getStatsXML'), totalTime: tt, date: new Date()).save()  
        statss
    }   
    
}
